package com.cd.queue.aspect;

import com.cd.common.domain.LoginUser;
import com.cd.common.util.AuthUtils;
import com.cd.common.util.SpringUtils;
import com.cd.queue.annotation.QueueOperationLog;
import com.cd.queue.api.QueueService;
import com.cd.queue.jpa.domain.QueueOperationRecord;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Aspect
@Component
public class QueueLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(QueueLogAspect.class);

    // 定义切点：拦截QueueService中需要记录日志的方法
    @Pointcut("execution(* com.cd.queue.api.QueueService.addNormal(..)) || " +
            "execution(* com.cd.queue.api.QueueService.revokeNormal(..)) || " +
            "execution(* com.cd.queue.api.QueueService.poll(..)) || " +
            "execution(* com.cd.queue.api.QueueService.clear(..)) || " +
            "execution(* com.cd.queue.api.QueueService.batchAdd(..))")
    public void queueOperationPointcut() {}

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(operationLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, QueueOperationLog operationLog, Object jsonResult) {
        handleLog(joinPoint, operationLog, null, jsonResult);
    }

    protected void handleLog(final JoinPoint joinPoint, QueueOperationLog operationLog, final Exception e, Object jsonResult) {
        try {
            // 获取当前的用户
            LoginUser loginUser = AuthUtils.getLoginUser();

            // *========写入日志=========*//
            Object[] args = joinPoint.getArgs(); // 获取所有入参
            QueueOperationRecord queueOperationRecord = new QueueOperationRecord();
            queueOperationRecord.setOrganiser(null);
            queueOperationRecord.setUsername(joinPoint.getArgs()[0].toString());
            queueOperationRecord.setOperator(loginUser.getUsername());
            queueOperationRecord.setOperationTime(new Date());
            String operationText=getOperationText(operationLog.action(),joinPoint.getArgs(),loginUser.getUsername());
            queueOperationRecord.setOperation(operationText);

            // 设置方法名称
            SpringUtils.getBean(QueueService.class).saveRecord(queueOperationRecord);
        } catch (Exception exp) {
            // 记录本地异常日志
            logger.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    private String getOperationText(String action, Object[] args,String loginUserName) {
        switch (action) {
            case "addNormal":
                return "["+loginUserName+"]为队列"+"添加了["+args[1]+"]用户";
            case "revokeNormal":
                return "移除用户";
            case "poll":
                return "["+loginUserName+"]执行了叫号    操作:"+args[1];
            case "clear":
                return "["+loginUserName+"]清空了队列";
            case "batchAdd":
                return "["+loginUserName+"]为队列"+"批量添加了"+((List<String>)args[1]).toString()+"用户";
            default:
                return "方法未命名";
        }
    }

}
